package com.roam.utils;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
@Service
public class GaoDeAPI {
    private static String key = "365fc1b2d33dd741c8ed97d36b7ebb08";
    public  String getRegion(String name,String city){
        String region = "";
        try{
            String url="https://restapi.amap.com/v5/place/text?keywords="+name+"&key="+key+"&region="+city;
            URL apiUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            if(responseCode==HttpURLConnection.HTTP_OK){
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line= reader.readLine())!=null){
                    response.append(line);
                }
                reader.close();
                JSONObject json = JSON.parseObject(response.toString());
                JSONArray pois = json.getJSONArray("pois");
                for(int i =0 ;i<pois.size();i++){
                    JSONObject poi = pois.getJSONObject(i);
                    String realName = poi.getString("name");
                    if(realName.equals(name)){
                        region = poi.getString("adname");
                        return region;
                    }
                }
                for(int i =0 ;i<pois.size();i++){
                    JSONObject poi = pois.getJSONObject(i);
                    String adName = poi.getString("adame");
                    if(adName!=null){
                        return adName;
                    }
                }
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
                String error =null;
                return error;
        }
    }

//    public static void main(String[] args) {
//         String TEMP=getRegion("黄金海岸水上乐园","广州");
//         System.out.println(TEMP);
//    }
}
